import React, { useState, useEffect } from 'react';
import { Space, Table, Switch, Tree, Input, Select, Button, } from 'antd';
// import { SearchOutlined } from '@ant-design/icons';
import userStyles from '../css/User.module.scss'
import commonStyles from '../css/Common.module.scss'


import { systemUser, userDeptTree } from '../../service/user'

const columns = [
    // {
    //     title: '用户编号',
    //     dataIndex: 'key',
    // },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '部门',
      dataIndex: 'dept',
      key: 'dept',
      render: (record) => (
        <Space size="middle">
          {record.deptName}
        </Space>
      ),
    },
    {
      title: '手机号码',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: () => (
        <Space size="middle">
          <Switch size="small" defaultChecked />
        </Space>
      ),
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle" v-if="record.admin">
          <a>修改</a>
          <a>删除</a>
        </Space>
      ),
    },
  ];


function User() {
    const [selectionType, setSelectionType] = useState('checkbox');
    const [data, setData] = useState([]);
    const [userValue, setUserValue] = useState('');
    const [phoneValue, setPhoneValue] = useState('');
    const [statusValue, setStatusValue] = useState('');
    const [treeData, setTreeData] = useState([]);
    const [position, setPosition] = useState('end');


    useEffect(() => {
        fetchTableData();
        fetchDeptTree();
    }, []);
    const fetchDeptTree = async () => {
      try {
          const treeRes = await userDeptTree()
          if (treeRes.data.length > 0) {
            treeRes.data.map((item) => {
              item.title = item.label
              item.key = item.id
              getChildren(item.children || [])
            })
            setTreeData(treeRes.data)
          }
      } catch (error) {
          console.error('Error fetching data:', error);
      }
    }

    const fetchTableData = async (deptId = '') => {
        try {
            let params = {
                pageNum: 1,
                pageSize: 10,
                deptId: deptId || '',
                userName: userValue || '',
                phonenumber: phoneValue || '',
                status: statusValue,
            
            }
            const res = await systemUser(params)
            setData(res && res.rows || [])
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const getChildren = (treeData) => {
      treeData.map((item) => {
        item.title = item.label
        item.key = item.id
        if (item.children && item.children.length > 0) {
          getChildren(item.children)
        }
      })
    }
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
          disabled: ['Disabled User'].includes(record.name),
          name: record.name,
        }),
      };

      const onSelect = (selectedKeys, info) => {
        fetchTableData(selectedKeys.join(''))

      };

      const onCheck = (checkedKeys, info) => {
        console.log('onCheck', checkedKeys, info);
      };

      const searchTable = () => {
        console.log('userValue', userValue, statusValue)
        fetchTableData()
      }

      const handleChange = (value) => {
        setStatusValue(value)
      };

      const userChange = (e) => {
        setUserValue(e.target.value)
      };
      const phoneChange = (e) => {
        setPhoneValue(e.target.value)
      };

  return <div className={userStyles.userContainer}>
        <Tree
          onSelect={onSelect}
          onCheck={onCheck}
          treeData={treeData}
          className={userStyles.leftTree}
        />
        <div className={userStyles.rightContent}>
          <div className={userStyles.searchBox}>
            <Input placeholder="请输入用户名称"
              style={{
                width: 200,
              }}
              value={userValue} allowClear onChange={userChange}/>
            <Input placeholder="请输入手机号码"
              style={{
                width: 200,
              }}
              className={commonStyles.ml16} value={phoneValue} allowClear onChange={phoneChange} />
            <Select
              value={statusValue}
              placeholder="请选择"
              onChange={handleChange}
              className={commonStyles.ml16}
              style={{
                width: 200,
              }}
              options={[
                {
                  value: 0,
                  label: '正常',
                },
                {
                  value: 1,
                  label: '停用',
                },
              ]}
            />
            <Button type="primary" className={commonStyles.ml16} iconPosition={position} onClick={() => searchTable()}>
              Search
            </Button>

          </div>
          
          <Table rowSelection={{
            type: selectionType,
            ...rowSelection,
          }} columns={columns}
          className={userStyles.rightTable}
          dataSource={data} />
        </div>
    </div>
}

export default User
